package com.tong.cloud.feign.contract;

import com.tong.cloud.feign.processor.AnnotatedClassProcessor;
import com.tong.cloud.feign.processor.BasicAuthClassProcessor;
import com.tong.cloud.feign.processor.CustomClientClassProcessor;
import com.tong.cloud.feign.processor.HeaderClassProcessor;
import feign.MethodMetadata;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
import org.springframework.cloud.openfeign.support.SpringMvcContract;
import org.springframework.core.io.ResourceLoader;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class CustomContract extends SpringMvcContract {
    private ResourceLoader resourceLoader;

    private List<AnnotatedClassProcessor> annotatedClassProcessors;


    public CustomContract(List<AnnotatedParameterProcessor> parameterProcessors) {
        super(parameterProcessors);
        annotatedClassProcessors = getCustomAnnotatedClassProcessors();
    }

    @Override
    protected void processAnnotationOnClass(MethodMetadata data, Class<?> clz) {
        log.info("start custom class contract ....");
        super.processAnnotationOnClass(data, clz);
        for (AnnotatedClassProcessor processor : annotatedClassProcessors) {
            if (clz.isAnnotationPresent(processor.getAnnotationType())) {
                processor.process(data, clz);
            }
        }
    }

    @Override
    protected void processAnnotationOnMethod(MethodMetadata data, Annotation methodAnnotation, Method method) {
        log.info("start custom method contract ....");
        super.processAnnotationOnMethod(data, methodAnnotation, method);
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
        super.setResourceLoader(resourceLoader);
    }

    private List<AnnotatedClassProcessor> getCustomAnnotatedClassProcessors() {
        List<AnnotatedClassProcessor> annotatedClassResolvers = new ArrayList<>();
        annotatedClassResolvers.add(new HeaderClassProcessor(this.resourceLoader));
        annotatedClassResolvers.add(new CustomClientClassProcessor());
        annotatedClassResolvers.add(new BasicAuthClassProcessor());
        return annotatedClassResolvers;
    }

}
